<?php

/**
 * celebrityPk actions.
 *
 * @package    iEasy
 * @subpackage celebrityPk
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class celebrityPkActions extends sfActions
{
    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request)
    {
        //        $this->forward('default', 'module');
    }

    public function executeVote(sfWebRequest $request)
    {
        $ip = utility::getRequestIp($request);
        $userId = $this->getUser()->getAttribute('userId');
        if ($userId == '' || $userId == null) $userId = 1;
        $pkId = $request->getParameter("pkId");
        $log = Doctrine_Core::getTable('CelebrityPklog')->createQuery('c')
                ->addWhere('c.user_ip=?', $ip)->addWhere('c.pk_id=?', $pkId)
                ->addOrderBy('c.create_time desc')->fetchOne();
        if ($log != null) {
            $now = time();
            $latestLogTime = strtotime($log->getCreateTime());
            $diff = $now - $latestLogTime;
            if (($diff / 60) < 5)
                return $this->renderText('0');
            //            return $this->renderComponent('celebrityPk', 'pkbox');
        }


        $idx = $request->getParameter("idx");
        $pk = @Doctrine_core::getTable("CelebrityPK")
                ->find($pkId);
        $celebrityId = $pk->getCelebrity1Id();
        switch ($idx)
        {
            case '1':
                $pk->setCount1I($pk->getCount1I() + 1);
                break;
            case '2':
                $pk->setCount2I($pk->getCount2I() + 1);
                $celebrityId = $pk->getCelebrity2Id();
                break;
        }
        $pk->save();

        try {
            $log = new CelebrityPklog();
            $log->setPkId($pkId);
            $log->setUserId($userId);
            $log->setUserIp($ip);
            $log->setCelebrityId($celebrityId);
            $log->setCreateTime(date(Constants::$DEFAULT_DATETIME_FORMAT));
            $log->save();
        } catch (Exception $e) {
            echo $e->getTraceAsString();
        }

        if ($request->isXmlHttpRequest()) {
            return $this->renderComponent('celebrityPk', 'pkbox');
        }
    }
}
